package com.le.tester.javaThink.fourth.concurrency;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * createTime：2021/10/20 11:51
 * description：原子类atomicityInteger,多线程下保证了原子性
 */
public class AtomicityIntegerTest implements Runnable {

    //init
    private AtomicInteger i = new AtomicInteger(0);

    public int getValue() {
        return i.get();
    }

    private void evenIncrement() {
        i.addAndGet(2);
    }

    @Override
    public void run() {
        while (true)
            evenIncrement();
    }

    public static void main(String[] args) {
        //已经不建议使用了,五秒后执行
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                System.err.println("Aborting");
                System.exit(0);
            }
        }, 5000);

        ExecutorService service = Executors.newCachedThreadPool();
        AtomicityIntegerTest atomicityIntegerTest = new AtomicityIntegerTest();
        service.submit(atomicityIntegerTest);

        while (true) {
            int value = atomicityIntegerTest.getValue();
            //筛选偶数
            if (value % 2 != 0) {
                System.out.println(value);
                System.exit(0);
            }
        }
    }
}
